package web

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"ocr/ocr"
	"ocr/ocrV1"
	"strconv"
)

func GeneralBasicOCRHandler(rw http.ResponseWriter, req *http.Request) {
	var request = ocr.NewGeneralBasicOCRRequest()
	imageUrl := req.FormValue("image_url")
	scene := req.FormValue("scene")
	languageType := req.FormValue("languageType")
	isPdf, _ := strconv.ParseBool(req.FormValue("is_pdf"))
	pdfPageNumber, _ := strconv.ParseUint(req.FormValue("pdfPageNumber"), 10, 64)
	isWords, _ := strconv.ParseBool(req.FormValue("is_words"))

	request.ImageUrl = &imageUrl
	request.Scene = &scene
	request.LanguageType = &languageType
	request.IsPdf = &isPdf
	request.PdfPageNumber = &pdfPageNumber
	request.IsWords = &isWords

	if imageUrl == "" {
		file, _, err := req.FormFile("image_file")
		if err != nil {
			log.Println(err.Error())
			return
		}
		bytes, err := ioutil.ReadAll(file)
		if err != nil {
			log.Println(err.Error())
			return
		}
		imageBase64 := base64.StdEncoding.EncodeToString(bytes)
		request.ImageBase64 = &imageBase64
	}

	response, err := ocr.GeneralBasicOCR(request)
	if err != nil {
		log.Println(err.Error())
		return
	}
	fmt.Printf("%s", response.ToJsonString())
	fmt.Fprintf(rw, response.ToJsonString())
}

func GeneralBasicOCRHandlerV1(rw http.ResponseWriter, req *http.Request) {
	gb := ocrV1.GeneralBasic{}
	input := map[string]string{}

	input["image_url"] = req.FormValue("image_url")
	input["scene"] = req.FormValue("scene")
	input["language_type"] = req.FormValue("language_type")
	input["is_pdf"] = req.FormValue("is_pdf")
	input["pdf_page_number"] = req.FormValue("pdf_page_number")
	input["is_words"] = req.FormValue("is_words")

	if input["image_url"] == "" {
		file, _, err := req.FormFile("image_file")
		if err != nil {
			log.Println(err.Error())
			return
		}
		bytes, err := ioutil.ReadAll(file)
		if err != nil {
			log.Println(err.Error())
			return
		}
		imageBase64 := base64.StdEncoding.EncodeToString(bytes)
		input["image_base64"] = imageBase64
	}

	response, err := gb.Ocr(input)
	if err != nil {
		log.Println(err.Error())
		return
	}
	fmt.Printf("%s", response)
	fmt.Fprintf(rw, response)
}
